package com.thinkit.bigdata.web.controller.audioSearch;

import com.google.common.base.Strings;
import com.thinkit.bigdata.core.ConfigHelper;
import com.thinkit.bigdata.core.util.DateFormatUtil;
import com.thinkit.bigdata.core.util.TaskUtil;
import com.thinkit.bigdata.core.util.es.ESUtil;
import com.thinkit.bigdata.core.util.excel.XlsUtil;
import com.thinkit.bigdata.web.coremet.SystemStatic;
import com.thinkit.bigdata.web.model.BaseEntity;
import com.thinkit.bigdata.web.model.perCenter.PendingTaskModel;
import com.thinkit.bigdata.web.model.result.HtmlResult;
import com.thinkit.bigdata.web.service.audioSearch.TaskAudioSeaService;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.*;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 *
 * Created by hccl on 2018/9/18.
 */
@RestController
@RequestMapping("/task-audio-search")
public class TaskAudioSearch {

    private static Logger logger = Logger.getLogger(TaskAudioSearch.class);

    @Resource
    private TaskAudioSeaService taskAudioSeaService;

    @Resource
    private ESUtil esUtil;

    @RequestMapping(value = "/get-data-by-mes", method = RequestMethod.POST)
    public HtmlResult searchData(HttpServletRequest request) {
        String logTxt = "【任务音频检索方法】";
        logger.info(logTxt);
        String pageNum = request.getParameter("pageNum");//起始页
        String pageSize = request.getParameter("pageSize");//每页条数
        String sortName = request.getParameter("sortName");//录音流水
        String sortOrder = request.getParameter("sortOrder");//录音流水
        logger.info(logTxt + "pageNum = " + pageNum);
        logger.info(logTxt + "pageSize = " + pageSize);
        logger.info(logTxt + "sortName = " + sortName);
        logger.info(logTxt + "sortOrder = " + sortOrder);
        return taskAudioSeaService.searchData(request);
    }

    @RequestMapping(value = "/export-data-mes", method = RequestMethod.POST)
    public void exportMyAss(HttpServletRequest request, HttpServletResponse response) {
        String logTxt = "【话单信息-导出】";
        logger.info(logTxt);
        try {
            String workId = request.getParameter("workId");//质检任务名称
            String sortName = request.getParameter("sortName");//录音流水
            String sortOrder = request.getParameter("sortOrder");//录音流水
            BoolQueryBuilder boolQuery = taskAudioSeaService.getQuery(logTxt, request);
            List<PendingTaskModel> taskModelList = new ArrayList<>();
            //总条数
            Integer sum = SystemStatic.crud.queryQBuilderAllByMes(SystemStatic.AUDIO_ES_INDEX, SystemStatic.AUDIO_ES_TYPE, boolQuery);
            //单词查询条数
            int excleMax = ConfigHelper.getInt("export.data.sheet.max.number", 1000);
            List<Integer> pageTout = TaskUtil.formatSum(sum, excleMax);//todo最后一个数字需要特殊处理:6022
            String[] includes = new String[]
                    {
                            "serialNumber",
                            "voiceInfo",
                            "workScores.workId",
                            "workScores.workName",
                            "workScores.proStatus",
                            "workScores.proUserName",
                            "workScores.proFlag",
                            "workScores.workScore",
                            "workScores.updateTime",
                            "workScores.preQuality"
                    };
            for (Integer aPageTout : pageTout) {
                List<String> docList = SystemStatic.crud.queryMapQBuilderRetRuleAndWork(
                        SystemStatic.AUDIO_ES_INDEX,
                        SystemStatic.AUDIO_ES_TYPE,
                        aPageTout,
                        excleMax,
                        boolQuery,
                        SystemStatic.crud.formatCloumn(sortName, SystemStatic.AUDIO_ES_INDEX),
                        sortOrder,
                        includes
                );
                if (docList.isEmpty()) continue;
                taskModelList.addAll(esUtil.formatModel(docList, workId));
            }
            logger.info(logTxt + "获取数据条数为：" + taskModelList.size());
            //生成excel
            HSSFWorkbook workbook = new HSSFWorkbook();//创建一个xls文档对象
            HSSFSheet sheet = workbook.createSheet();//创建一个工作薄对象
            //设置标题和列名称
            String[] header = {"编号", "省份", "质检任务名称", "质检任务类型", "任务状态",  "质检属性", "最新人工质检员", "呼叫类型", "录音流水",
                    "坐席班组", "坐席工号",  "坐席姓名", "客户号码", "受理号码", "通话时长(秒)", "通话开始时间", "通话结束时间",
                    "语音入库时间", "挂机方", "是否重复来电", "满意度", "客户归属地", "客户星级", "重要客户", "分值"};
            String title = "话单信息列表";
            XlsUtil.setTableTitleHeader(workbook, sheet, Arrays.asList(header), title);
            //获取表文样式
            HSSFCellStyle tableStyle = XlsUtil.getTableStyle(workbook);
            HSSFRow row2;
            HSSFCell cell2;
            for (int j = 0; j < taskModelList.size(); j++) {
                PendingTaskModel taskMode = taskModelList.get(j);
                row2 = sheet.createRow(3 + j);
                for (int i = 0; i < header.length; i++) {
                    cell2 = row2.createCell(i);
                    cell2.setCellStyle(tableStyle);
                    switch (i) {
                        case 0:
                            cell2.setCellValue(new HSSFRichTextString((j + 1) + ""));
                            break;
                        case 1:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getProvince()));
                            break;
                        case 2:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getWorkName()));
                            break;
                        case 3:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getPreQuality() == 0 ? "自动质检" : "专项质检"));
                            break;
                        case 4:
                            cell2.setCellValue(new HSSFRichTextString(esUtil.changeState(taskMode.getProStatus())));
                            break;
                        case 5:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getProFlag() == BaseEntity.PROFLAG_SYS ? "系统质检" : "人工质检"));
                            break;
                        case 6:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getProUserId()));
                            break;
                        case 7:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getCallDirection() == 0 ? "呼入" : "呼出"));
                            break;
                        case 8:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getSerialNumber()));
                            break;
                        case 9:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getSeatGroup()));
                            break;
                        case 10:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getSeatId()));
                            break;
                        case 11:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getSeatName()));
                            break;
                        case 12:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getCustomerNum()));
                            break;
                        case 13:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getProPhoneNum()));
                            break;
                        case 14:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getHoldDuration() + ""));
                            break;
                        case 15:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getCallStartTime()));
                            break;
                        case 16:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getCallEndTime()));
                            break;
                        case 17:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getInputTime()));
                            break;
                        case 18:
                            cell2.setCellValue(new HSSFRichTextString(esUtil.changeOnHook(taskMode.getOnHook())));
                            break;
                        case 19:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getReCallFlag() == 0 ? "否" : "是"));
                            break;
                        case 20:
                            cell2.setCellValue(new HSSFRichTextString(esUtil.changeSatisfaction(taskMode.getSatisfaction())));
                            break;
                        case 21:
                            Map<String,Object> map =  SystemStatic.PROVINCE_CITY_MAP;
                            Map<String, String> citys = (Map<String, String>) map.get(taskMode.getProvinceCode());
                            String city = citys.get(taskMode.getCustomerloc());
                            cell2.setCellValue(new HSSFRichTextString(Strings.isNullOrEmpty(city) ? taskMode.getCustomerloc() : city));
                            break;
                        case 22:
                            cell2.setCellValue(new HSSFRichTextString(esUtil.changeCustomerLevel(taskMode.getCustomerLevel())));
                            break;
                        case 23:
                            String customerSign = "";
                            if (!Strings.isNullOrEmpty(taskMode.getCustomerSign())) {
                                customerSign = taskMode.getCustomerSign().equals("0") ? "否" : "是";
                            }
                            cell2.setCellValue(new HSSFRichTextString(customerSign));
                            break;
                        case 24:
                            cell2.setCellValue(new HSSFRichTextString(taskMode.getWorkScore() + ""));
                            break;
                    }
                }
            }
            for (int i = 0; i < header.length; i++) {
                sheet.autoSizeColumn((short) i, true);//自动调整列宽
            }
            String fileName = title + "_" + DateFormatUtil.getNowTime() + ".xls";
            // 清空response
            response.reset();
            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));  //转码之后下载的文件名不会出现中文乱码
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/audio-nlp-status", method = RequestMethod.POST)
    public HtmlResult audioNlpStatus(
            @RequestParam(value = "serialNumber") final String serialNumber,
            @RequestParam(value = "workId") final String workId,
            @RequestParam(value = "type") final String type
    ) {
        String logTxt = "【获取任务nlp处理状态】";
        logger.info(logTxt);
        logger.info(logTxt + "serialNumber = " + serialNumber);
        logger.info(logTxt + "workId = " + workId);
        logger.info(logTxt + "type = " + type); // test/work
        return taskAudioSeaService.audioNlpStatus(serialNumber, workId, type);
    }
}
